package com.yuyou.tas.admin.service.impl;

import com.yuyou.tas.admin.mapper.AuthResourceMapper;
import com.yuyou.tas.admin.service.IAuthResourceService;
import com.yuyou.tas.admin.service.IAuthRoleResourceRelationService;
import com.yuyou.tas.admin.vo.resp.RespAuthResource;
import com.yuyou.tas.admin.vo.resp.RespAuthRoleResource;
import com.yuyou.tas.service.api.admin.entity.AuthResource;
import com.yuyou.tas.service.api.admin.entity.AuthRoleResourceRelation;
import com.yuyou.tas.util.tool.BeanUtils;
import com.yuyou.tas.util.tool.DateUtil;
import com.yuyou.tas.util.tool.DefindBeanUtils;
import com.yuyou.tas.util.tool.Sequence;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**
 * Created by yujin.liu on 2018/1/23.
 */
@Service
public class AuthResourceServiceImpl implements IAuthResourceService{

    @Autowired
    private AuthResourceMapper authResourceMapper;

    @Autowired
    private IAuthRoleResourceRelationService authRoleResourceRelationService;


    @Override
    public List<RespAuthRoleResource> findAllAuthResourceWithChildren(Long authRoleId){
        List<RespAuthResource> authResourceList = authResourceMapper.findAuthResourceList();

        // 角色资源列表
        List<AuthRoleResourceRelation> roleResourceRelationList = authRoleResourceRelationService.findRoleResourceRelationByAuthRoleId(authRoleId);
        List<Long> authResourceIdList = BeanUtils.toList(roleResourceRelationList, "authResourceId");


        List<RespAuthRoleResource> respAuthRoleResourceList = toRespAuthResource(authResourceList,authResourceIdList, 0L);

        return respAuthRoleResourceList;
    }

    @CacheEvict(value = "CacheOfResource",allEntries = true )
    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public void saveAuthRoleResourceList(Long authRoleId, List<Long> authResourceIds){

        // 先删除后插入
        authRoleResourceRelationService.deleteByAuthRoleId(authRoleId);

        List<AuthRoleResourceRelation> roleResourceRelationList = new ArrayList<>(authResourceIds.size());

        for(Long authResourceId : authResourceIds){
            AuthRoleResourceRelation authRoleResourceRelation = new AuthRoleResourceRelation();
            authRoleResourceRelation.setId(Sequence.getSequence().nextId());
            authRoleResourceRelation.setAuthRoleId(authRoleId);
            authRoleResourceRelation.setAuthResourceId(authResourceId);
            authRoleResourceRelation.setCreateTime(DateUtil.now());
            authRoleResourceRelation.setUpdateTime(DateUtil.now());

            roleResourceRelationList.add(authRoleResourceRelation);
        }

        authRoleResourceRelationService.batchInsertRoleResourceRelation(roleResourceRelationList);
    }



    private List<RespAuthRoleResource> toRespAuthResource(List<RespAuthResource> authResourceList, List<Long> authResourceIdList, Long parentId){
        List<RespAuthRoleResource> respAuthRoleResourceList = new ArrayList<>(10);

        for(RespAuthResource authResource :  authResourceList ){
            if(parentId.equals(authResource.getParentId())){
                RespAuthRoleResource respAuthRoleResource = new RespAuthRoleResource();
                DefindBeanUtils.copyProperties(authResource, respAuthRoleResource);
                // 判断是否选中
                respAuthRoleResource.setChecked(authResourceIdList.contains(authResource.getId()) ? true : false);
                respAuthRoleResourceList.add(respAuthRoleResource);
                List<RespAuthRoleResource> childrenList = toRespAuthResource(authResourceList ,  authResourceIdList, authResource.getId());
                if(childrenList.size() > 0 ){
                    respAuthRoleResource.setChildren(childrenList);
                }
            }
        }
        if(!CollectionUtils.isEmpty(respAuthRoleResourceList)){
            respAuthRoleResourceList.sort(Comparator.comparing(respAuthRoleResource -> {
                if(respAuthRoleResource.getSort() == null){
                    return 1 ;
                }else{
                    return respAuthRoleResource.getSort();
                }
            }));
        }
        /*Collections.sort(respAuthRoleResourceList, new Comparator<RespAuthRoleResource>() {
            @Override
            public int compare(RespAuthRoleResource o1, RespAuthRoleResource o2) {
                if(o1.getSort() == null || o2.getSort() == null ){
                    return 0 ;
                }
                return o1.getSort() - o2.getSort() ;
            }
        });*/

        return respAuthRoleResourceList;
    }


	@Override
	public List<RespAuthResource> findAuthResourceByUserId(Long authUserId) {
		return authResourceMapper.findAuthResourceByUserId(authUserId);
	}

    @Cacheable(value = "CacheOfResource",key = "#userId")
    @Override
    public List<RespAuthRoleResource> findAuthResourceByUserIdFromCache(Long userId) {
        List<RespAuthResource> authResourceList = authResourceMapper.findAuthResourceByUserId(userId);
        List<Long> authResourceIdList = BeanUtils.toList(authResourceList, "id");
        List<RespAuthRoleResource> respAuthRoleResourceList = toRespAuthResource(authResourceList,authResourceIdList, 0L);

        return respAuthRoleResourceList;
    }

}
